package com.jack.blog.controller;

import com.jack.blog.cache.MessageServiceCache;
import com.jack.blog.vo.MessageVo;
import com.jack.blog.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("user/{uid}/blog/{bid}")
public class MessageController {
    @Autowired
    private MessageServiceCache messageServiceCache;

    @PostMapping("/message")
    @ResponseBody
    public Response addMessage(@PathVariable("uid")int uid,@PathVariable("bid") int bid, @RequestBody MessageVo messageVo){
        Response response=new Response();
        try{
            MessageVo message = messageServiceCache.addMessage(uid,bid, messageVo);
            response.setMsg("感谢你的留言!");
            response.setStatus(200);
            response.setData(message);
        }catch (IllegalArgumentException i){
            response.setMsg(i.getMessage());
            response.setStatus(400);
        }
        catch (Exception e){
            e.printStackTrace();
            response.setMsg("出错洛!");
            response.setStatus(500);
        }
        return response;
    }

    @PostMapping("/message/{mid}/reply")
    public String replyMessage(@PathVariable("uid")int uid,@PathVariable("bid")int bid, @PathVariable("mid") int mid, @RequestParam("content")String content, Model model){
        String url="/user/"+uid+"/messages";
        try {
            messageServiceCache.replyMessage(bid,mid,content);
            return "redirect:"+url;
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("error","send message error!");
            model.addAttribute("backUrl",url);
            return "error";
        }
    }

}
